import { createVNode, render } from 'vue'
import errorAlertVue from './main.vue'

interface Message{
    content: string,
    detail: string,
    title: string,
    type: string,
    callback:(action: 'confirm' | 'cancel') => void,
    resolve:(value?: unknown) => void,
    reject:(value?: unknown) => void
}

let container = null as any
const msgQueue:Message[] = []
let message:Message | {} = {}
let instance = null as any

const callback = (action:'confirm' | 'cancel'):void => {
    if (action === 'confirm') {
        (message as Message).resolve()
    } else if (action === 'cancel') {
        (message as Message).reject()
    }
    nextTodo()
}

const nextTodo = () => {
    if (msgQueue.length) {
        message = msgQueue.shift()
        for (const key in message) {
            if (Object.prototype.hasOwnProperty.call(message, key)) {
                if (key === 'resolve' || key === 'reject') continue
                instance.component.exposed.state[key] = message[key]
            }
        }
        instance.component.exposed.open()
    } else {
        instance.component.exposed.state.visible = false
        setTimeout(() => {
            message = {}
            instance = null
            container.remove()
            container = null
        }, 200)
    }
}

const ErrorAlert = function(content:string, detail:string, title:string, type:string) {
    return new Promise((resolve, reject) => {
        msgQueue.push({
            content,
            detail,
            title,
            type,
            callback,
            resolve,
            reject
        })

        if (!container) {
            container = document.createElement('div')
            container.id = 'error-alert'
            document.body.appendChild(container)
        }
        if (!instance) {
            instance = createVNode(errorAlertVue, {})
            render(instance, container)
            nextTodo()
        }
    })
}

export { ErrorAlert }
